package com.xiaobu.shop.aop;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.xiaobu.shop.domain.ResponseResult;
import com.xiaobu.shop.domain.query.QueryParameter;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import com.xiaobu.shop.annotation.EnableMyPage;
import java.util.List;

@Aspect
@Component
public class PageHelperAspect {

    @Pointcut("@annotation(com.xiaobu.shop.annotation.EnableMyPage)")
    public void serviceFindFunction(){}
    /**
     * 使用around方法 在执行查询方法前执行PageHelper.startWith
     * 在执行查询方法后 将结果封装到PageInfo中
     * @param proceedingJoinPoint
     * @return
     * @throws Throwable
     */
    @Around("serviceFindFunction()")
    public Object serviceImplAop(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {

        //获取连接点方法运行时的入参列表
        Object[] args = proceedingJoinPoint.getArgs();



        //获取连接点的方法签名对象
        Signature signature = proceedingJoinPoint.getSignature();
        
        //获取连接点所在的类的对象(实例)
        Object target = proceedingJoinPoint.getTarget();
        if (args[0] instanceof QueryParameter ) {
            QueryParameter queryParameter = (QueryParameter) args[0];
            Integer page = queryParameter.getPage();
            Integer pageSize = queryParameter.getPageSize();
            PageHelper.startPage(page,pageSize);
        }

        //返回值
        Object object = proceedingJoinPoint.proceed();
//        log.info("方法[{}]执行结束.",signature.getName());

        if(object instanceof List) {
            List objList = (List) object;
            PageInfo pageInfo = new PageInfo<>(objList);
            ResponseResult result =new ResponseResult(200,"查询成功",pageInfo);
            return result;
        }
        return object;

    }

}
